<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>校园订餐系统订单界面</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
    <link href="css/font-awesome.css?v=4.4.0" rel="stylesheet">
    <!-- jqgrid-->
    <link href="css/plugins/jqgrid/ui.jqgrid.css?0820" rel="stylesheet">
    <link href="css/animate.css" rel="stylesheet">
    <link href="css/style.css?v=4.1.0" rel="stylesheet">

    <!-- 引入 Moment.js CDN 1-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <style>
        /* Additional style to fix warning dialog position */
        #alertmod_table_list_2 {
            top: 900px !important;
        }

        .btn-primary,
        .btn-primary:hover,
        .btn-primary:active,
        .btn-primary:focus {
            background-color: transparent;
            border: none;
            color: #000000;
            padding: 0;
            box-shadow: none; /* 禁用按钮的阴影效果 */
            outline: none; /* 禁用点击时的轮廓线 */
        }
    </style>
</head>
<body class="gray-bg" th:with="consumer_id=${session.user}">
<input type="hidden" id="hiddenConsumerId" th:value="${consumer_id}">
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox ">
                <div class="ibox-title">
                    <h5>校园订餐系统订单列表</h5>
                </div>
                <div class="ibox-content">
                    <div class="jqGrid_wrapper">
                        <table id="table_list_2">
                            <thead>
                            <tr>
                                <th>订单id</th>
                                <th>顾客id</th>
                                <th>数量</th>
                                <th>菜品名</th>
                                <th>总价</th>
                                <th>取餐时间</th>
                                <th>取餐号</th>

                            </tr>
                            </thead>
                            <tbody id="alertmod_table_list_2">
                            <!-- 使用Thymeleaf迭代数据 -->
                            <tr th:each="reservation : ${data}">
                                <td th:text="${reservation.bill_id}"></td>
                                <td th:text="${reservation.consumer_id}"></td>
                                <td th:text="${reservation.quantity}"></td>
                                <td th:text="${reservation.dish_name}"></td>
                                <td th:text="${reservation.total}"></td>
                                <td th:text="${reservation.pickup_time}"></td>
                                <td th:text="${reservation.reservation_result}"></td>
                                <td th:text="${reservation.status}"></td>
                                <td>
                                    <!-- 按钮触发状态更新 -->
                                    <button class="btn btn-info" onclick="updateStatus('${reservation.bill_id}', '已取餐', this)">已取餐</button>

                                </td>

                            </tr>
                            </tbody>
                        </table>
                        <div id="pager_list_2"></div>
                    </div>
                    <!-- 添加此div以显示警告消息 -->
                    <div id="alertMessage" class="alert" style="display:none;"></div>
                    <button class="btn btn-success" onclick="refreshData()">刷新</button>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- 全局js -->
<script src="js/jquery.min.js?v=2.1.4"></script>
<script src="js/bootstrap.min.js?v=3.3.6"></script>
<!-- jqGrid -->
<script src="js/plugins/jqgrid/i18n/grid.locale-cn.js?0820"></script>
<script src="js/plugins/jqgrid/jquery.jqGrid.min.js?0820"></script>
<!-- 自定义js -->
<script src="js/content.js?v=1.0.0"></script>

<!-- Page-Level Scripts -->
<script>
    // 全局函数，用于显示警告信息
    function showAlert(message, alertType) {
        // 显示带有淡入淡出效果的警告
        $('#alertMessage').removeClass().addClass('alert ' + alertType).html(message).fadeIn().delay(3000).fadeOut();
    }

    // 全局函数，用于显示成功信息
    function showSuccessAlert(message) {
        showAlert(message, 'alert-success');
    }

    // 全局函数，用于显示错误信息
    function showErrorAlert(message) {
        showAlert(message, 'alert-danger');
    }
</script>
<script>
    $(document).ready(function () {
        $.jgrid.defaults.styleUI = 'Bootstrap';
        // 初始化jqGrid的函数
        function initJqGrid(data) {
            console.log('正在使用数据初始化 jqGrid：', data);

            $("#table_list_2").jqGrid({
                datatype: "local",
                data: data,
                height: 450,
                autowidth: true,
                shrinkToFit: true,
                rowNum: 20,
                rowList: [10, 20, 30],
                colNames: ['订单id', '顾客id', '数量', '菜品名', '总价', '取餐时间', '取餐号','状态','操作'],
                colModel: [
                    { name: "bill_id", index: "bill_id", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "consumer_id", index: "consumer_id", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "quantity", index: "quantity", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "dish_name", index: "dish_name", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "total", index: "total", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "pickup_time", index: "pickup_time", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "reservation_result", index: "reservation_result", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "status", index: "status", editable: true, width: 80, sorttype: "string", search: true },
                    { name: "deleteButton", index: "deleteButton", width: 60, align: "center", sortable: false, search: false, formatter: deleteButtonFormatter, label: '操作' },

                ],
                pager: "#pager_list_2",
                viewrecords: true,
                caption: "订单详细信息",
            });

            // Add selection
            $("#table_list_2").setSelection(4, true);
            // Setup buttons
            $("#table_list_2").jqGrid('navGrid', '#pager_list_2', {
                edit: true,
                add: true,
                del: true,
                search: true
            }, {
                height: 200,
                reloadAfterSubmit: true
            });
            console.log('jqGrid 初始化成功。');
        }

        // 使用AJAX请求从后端获取数据
        $.ajax({
            url: '/backend-api-endpoint/getReservationById?consumer_id=' + $('#hiddenConsumerId').val(),
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                // 初始化jqGrid
                initJqGrid(data);
            },
            error: function (error) {
                console.error('Error fetching data from the server:', error);
            }
        });
    });

    // 刷新数据函数
    function refreshData() {
        // 使用AJAX请求从后端获取数据
        $.ajax({
            url: '/backend-api-endpoint/getReservationById?consumer_id=' + $('#hiddenConsumerId').val(),
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                // 清空表格数据
                $("#table_list_2").jqGrid('clearGridData');
                // 添加新数据
                for (var i = 0; i < data.length; i++) {
                    $("#table_list_2").jqGrid('addRowData', i + 1, data[i]);
                }

                console.log('Data refreshed successfully.');
            },
            error: function (error) {
                console.error('Error fetching data from the server:', error);
            }
        });
    }


    function updateButtonFormatter(cellvalue, options, rowObject) {

        var buttonStatus = rowObject.status; // 这里假设按钮状态与订单状态相同

        // 如果按钮状态为已取餐，则按钮为禁用状态
        var buttonHtml = (buttonStatus === '已取餐') ? '<button class="btn btn-danger btn-sm" disabled>已取餐</button>' :
            '<button class="btn btn-danger btn-sm" onclick="updateStatus(\'' + rowObject.bill_id + '\', \'已取餐\', this)">取餐</button>';

        return buttonHtml;
    }


    function updateStatus(bill_id, status, button) {
        console.log('Updating status for bill_id:', bill_id, 'with status:', status);

        var requestData = { bill_id: bill_id, status: status };

        console.log('Sending request data:', requestData);

        $.ajax({
            url: '/backend-api-endpoint/updateReservationStatus',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(requestData),
            success: function (data) {
                console.log('Update successful. Response:', data);

                showSuccessAlert(data);

                // 更新按钮文本为已取餐
                $(button).text('已取餐');

                // 禁用按钮
                $(button).prop('disabled', true);
            },
            error: function (error) {
                console.error('Error updating status:', error);
                showErrorAlert('Failed to update status. Check the console for more details.');
            }
        });
    }


    function deleteButtonFormatter(cellvalue, options, rowObject) {
        return '<button class="btn btn-danger btn-sm" onclick="deleteReservation(\'' + rowObject.bill_id + '\')">删除</button>';
    }
    // 删除订单函数
    function deleteReservation(billId) {
        if (confirm("确定删除订单吗？")) {
            $.ajax({
                url: '/backend-api-endpoint/deleteReservation/' + billId,
                method: 'DELETE',
                success: function (data) {
                    showSuccessAlert(data);
                    // 刷新数据
                    refreshData();
                },
                error: function (error) {
                    showErrorAlert('删除订单失败。');
                    console.error('Error deleting reservation:', error);
                }
            });
        }
    }




</script>
</body>
</html>
